from xbmcswift2 import Plugin
from urllib2 import urlopen, Request, HTTPError, URLError
import re
import scraper
from BeautifulSoup import BeautifulSoup, SoupStrainer

plugin = Plugin()

@plugin.route('/')
def index():
    videos = scraper.get_channels()
    for video in videos:
	#scraper.log(video['path'])
        video['path'] = plugin.url_for('show_channel', channel=video['path'])
    return videos #plugin.finish(videos)

@plugin.route('/channels/<channel>/')
def show_channel(channel):
    tvshows = scraper.get_tvshows(channel)
    for show in tvshows:
	show['path'] = plugin.url_for('show_episode', episode=show['path'])
    return tvshows

@plugin.route('/channels/episodes/<episode>/')
def show_episode(episode):
    tvshows = scraper.get_showepisode(episode)
    for show in tvshows:
	show['path'] = plugin.url_for('play_episode', playshow=show['path'])
    return tvshows    

@plugin.route('/channels/episodes/episode/<playshow>/')
def play_episode(playshow):
    playlinks = scraper.get_showlink(playshow)
    return plugin.finish(playlinks)

def get_free_videos():
    url = 'http://apni.tv/channels/colors.html'
    tree = __get_tree(url)
    videos = []
    for li in tree.findAll('li', {'class': re.compile('ul-videos-li')}):
        videos.append({
            'label': li.img['title'],
            'thumbnail': __resize_icon(MAIN_URL + li.img['src']),
            'info': {'duration': li.span.string.strip()},
            'path': li.div.a['href'],
        })
    return videos

def __get_url(req):
	try:
		html = urlopen(req).read()
	except HTTPError, error:
		log('__urlopen HTTPError: %s' % error)
		raise NetworkError('HTTPError: %s' % error)
	except URLError, error:
		log('__urlopen URLError: %s' % error)
		raise NetworkError('URLError: %s' % error)
	return html
	
def log(msg):
    print('%s scraper: %s' % (MAIN_URL, msg))
if __name__ == '__main__':
    plugin.run()
